package com.arrogames.rgblabyrinth.game.camera {
	import ash.core.Engine;
	import ash.core.NodeList;
	import ash.core.System;
	
	import com.arrogames.lib.ash.rendering.RenderNode;
	import com.arrogames.lib.ash.rendering.RenderingSystem;
	
	import starling.display.DisplayObjectContainer;
	
	public class CameraRenderingSystem extends System{
		
		private var container:DisplayObjectContainer;
		private var camera:CameraNode;
		
		public function CameraRenderingSystem(container:DisplayObjectContainer) {
			this.container = container;
		}
		
		override public function addToEngine(engine:Engine):void {
			super.addToEngine(engine);
			
			var cameras:NodeList = engine.getNodeList(CameraNode);
			camera = cameras.head as CameraNode;
			cameras.nodeAdded.add(onCameraAdded);
			cameras.nodeRemoved.add(onCameraRemoved);
		}
		
		override public function update(time:Number):void {
			super.update(time);
			if (hasCamera()) {
				container.scaleX = camera.camera.zoom;
				container.scaleY = camera.camera.zoom;
				container.x = camera.position.x;
				container.y = camera.position.y;
			}
		}
		
		private function onCameraAdded(node:CameraNode):void {
			this.camera = node;
			container.scaleX = node.camera.zoom;
			container.scaleY = node.camera.zoom;
			container.x -= node.position.x;
			container.y -= node.position.y;
		}
		
		private function onCameraRemoved(node:CameraNode):void {
			this.camera = null;
			container.scaleX = 1;
			container.scaleY = 1;
			container.x = 0
			container.y = 0;
		}
		
		private function hasCamera():Boolean {
			return camera != null;
		}
		
	}
}